<template>
  <div class="container info-container">
    <el-row :gutter="10">
      <el-col :lg="6" :md="6" :sm="24" :xl="24" :xs="24">
        <div class="card-container">
          <vab-card
            :body-style="{ padding: '5px' }"
            header="员工信息"
            shadow="hover"
          >
            <div class="info-user-info card-content-full">
              <div style="display: flex; justify-content: center">
                <div class="info-user-info-cert-img">
                  <el-image
                    fit="contain"
                    :src="state.staffForm.certImg"
                    style="cursor: pointer"
                    @click="openPictureCropperDialog"
                  />
                </div>
              </div>
              <div class="info-user-info-full-name">
                {{ state.staffForm.userName }}
              </div>
              <div class="info-user-info-description">
                {{ state.staffForm.remark }}
              </div>
              <ul class="info-user-info-list">
                <li>
                  员工编号：
                  {{ state.staffForm.labor }}
                </li>
                <li>
                  身份证号：
                  {{ state.staffForm.certNo }}
                </li>
                <li>
                  办公电话：
                  {{ state.staffForm.telephone }}
                </li>
                <li>
                  手机号码：
                  {{ state.staffForm.mobilePhone }}
                </li>
                <li>
                  员工状态：
                  {{ state.staffForm.statusDesc }}
                </li>
                <li>
                  邮箱：
                  {{ state.staffForm.email }}
                </li>
                <li>
                  性别：
                  {{ state.staffForm.userSexDesc }}
                </li>
                <li>
                  部门：
                  {{ state.staffForm.deptNames }}
                </li>
                <li>
                  位置：
                  {{ state.staffForm.location }}
                </li>
              </ul>
            </div>
          </vab-card>
        </div>
      </el-col>
      <el-col :lg="18" :md="18" :sm="24" :xl="24" :xs="24">
        <div class="card-container info-sysuser">
          <vab-card shadow="never">
            <div class="card-content-full">
              <el-tabs v-model="state.activeName" stretch type="border-card">
                <el-tab-pane label="账号信息" name="first">
                  <el-form
                    ref="sysUserFormRef"
                    label-width="100px"
                    :model="state.sysUserForm"
                    :rules="state.formRules"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="用户名称:" prop="id">
                          <el-input
                            v-model="state.sysUserForm.userName"
                            placeholder="请选择员工"
                            :readonly="
                              state.sysUserForm.userType === '1' ? true : false
                            "
                          >
                            <template
                              v-if="
                                state.sysUserForm.userType === '1'
                                  ? true
                                  : false
                              "
                              #append
                            >
                              <el-button
                                icon="Search"
                                @click="handleOpenStaffSelector"
                              >
                              </el-button>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="用户账号:" prop="userCode">
                          <el-input
                            v-model="state.sysUserForm.userCode"
                            :maxlength="16"
                            :show-word-limit="true"
                            type="text"
                          >
                            <template #append>
                              <el-button @click="handleUserNameChange">
                                <el-icon><i-ri-refresh-line /></el-icon>
                              </el-button>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="手机号码:" prop="phone">
                          <el-input
                            v-model="state.sysUserForm.phone"
                            type="text"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="用户编号:" prop="labor">
                          <el-input
                            v-model="state.sysUserForm.labor"
                            :maxlength="16"
                            :show-word-limit="true"
                            type="text"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="有效期限:" prop="validDate">
                          <el-date-picker
                            v-model="state.sysUserForm.validDate"
                            :editable="false"
                            placeholder="请选择有效期限"
                            type="date"
                            value-format="YYYY-MM-DD"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="用户类别:" prop="userType">
                          <easy-dict-select
                            ref="userTypeRef"
                            :default-value="state.sysUserForm.userType"
                            dict-code="1016"
                            show-all="N"
                            @change="handleUserTypeChange"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="用户状态:" prop="status">
                          <easy-dict-select
                            ref="userStatusRef"
                            :default-value="state.sysUserForm.status"
                            dict-code="1000"
                            show-all="N"
                            @change="handleUserStatusChange"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="允许删除:" prop="ifAllowDelete">
                          <el-radio
                            v-model="state.sysUserForm.ifAllowDelete"
                            label="Y"
                            >允许删除</el-radio
                          >
                          <el-radio
                            v-model="state.sysUserForm.ifAllowDelete"
                            label="N"
                            >不允许删除</el-radio
                          >
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="用户角色:" prop="roleIds">
                          <el-input
                            v-model="state.sysUserForm.roleNames"
                            placeholder="请选择用户角色"
                            :readonly="true"
                          >
                            <template #append>
                              <el-button
                                @click="handleOpenRolePicker"
                                icon="Search"
                              >
                              </el-button>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="6">
                        <el-form-item label="头像:" prop="avatarImg">
                          <el-avatar
                            :size="100"
                            :src="state.sysUserForm.avatar"
                            style="cursor: pointer"
                            @click="handleOpenSysUserAvatarCropper"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="18">
                        <el-button
                          type="warning"
                          icon="refresh-left"
                          @click="handleResetSysUserAvatar"
                          >重置</el-button
                        >
                      </el-col>
                    </el-row>
                    <el-form-item>
                      <el-button
                        icon="circle-check"
                        type="primary"
                        @click="onSave"
                        >确认保存</el-button
                      >
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="重置密码" name="second">
                  <el-form
                    ref="resetPasswordFormRef"
                    label-width="100px"
                    :model="state.resetPasswordFormData"
                    :rules="state.resetPasswordFormRules"
                  >
                    <el-form-item label="新密码:" prop="password">
                      <el-input
                        v-model="state.resetPasswordFormData.password"
                        :maxlength="16"
                        :show-word-limit="true"
                        type="text"
                      />
                    </el-form-item>
                    <el-form-item label="确认密码:" prop="confirmPassword">
                      <el-input
                        v-model="state.resetPasswordFormData.confirmPassword"
                        :maxlength="16"
                        :show-word-limit="true"
                        type="text"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        icon="circle-check"
                        type="primary"
                        @click="onResetPassword"
                        >确认重置</el-button
                      >
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="账号绑定" name="three">
                  <div class="info-item">
                    <el-icon style="color: #3492ed"><i-ri-qq-line /></el-icon>
                    <div class="info-item-content">
                      <div>绑定QQ</div>
                      <div class="info-item-content-second">
                        当前未绑定绑定QQ账号
                      </div>
                    </div>
                    <el-link type="primary">更换绑定</el-link>
                  </div>
                  <el-divider />
                  <div class="info-item">
                    <el-icon style="color: #4daf29"
                      ><i-ri-wechat-2-line
                    /></el-icon>
                    <div class="info-item-content">
                      <div>绑定微信</div>
                      <div class="info-item-content-second">
                        当前未绑定绑定微信账号
                      </div>
                    </div>
                    <el-link type="primary">更换绑定</el-link>
                  </div>
                  <el-divider />
                </el-tab-pane>
              </el-tabs>
            </div>
          </vab-card>
        </div>
      </el-col>
    </el-row>
    <PictureCropper
      ref="sysUserCropperRef"
      @confirm="handleSysUserCropperConfirm"
    />
    <PictureCropper
      ref="pictureCropperRef"
      @confirm="handlePictureCropperConfirm"
    />
    <StaffPicker
      ref="staffRef"
      :ingore-binding="true"
      :single-select="true"
      title="选择员工"
      width="60%"
      @change="handleUserSelect"
    />
    <RolePicker ref="roleRef" width="20%" @change="handleRoleSelect" />
  </div>
</template>

<script setup name="UserCenter">
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/modules/user";
import { queryStaff, updateStaff } from "@/api/admin/org/staff";
import {
  updateUser,
  queryUser,
  updateResetPassword,
  validUserCode
} from "@/api/admin/org/sysuser/";
import { validMobilePhone } from "@/utils/rules";
import pinyin from "js-pinyin";
import dayjs from "dayjs";
import EasyDictSelect from "@/components/dictSelect.vue";
import StaffPicker from "@/components/staffPicker.vue";
import RolePicker from "@/components/rolePicker.vue";
import PictureCropper from "@/components/pictureCropper.vue";
import { cloneObject } from "@/utils/common";
import { useMessage } from "@/hooks/message";
import { ref, reactive } from "vue";
import certDefaultImg from "@/assets/empty_images/data_empty.png";
import userDefaultAvatar from "@/assets/cropper_images/user.gif";

const userStore = useUserStore();

const pictureCropperRef = ref();

const { getUserid: userid } = storeToRefs(userStore);
const { getUsername: usename } = storeToRefs(userStore);
const { getAvatar: avatar } = storeToRefs(userStore);

const sysUserCropperRef = ref(null);
const sysUserFormRef = ref(null);
const resetPasswordFormRef = ref(null);
const roleRef = ref(null);
const staffRef = ref(null);
const userTypeRef = ref(null);
const userStatusRef = ref(null);

const state = reactive({
  activeName: "first",
  staffForm: {
    id: "",
    labor: "--",
    userName: "未绑定",
    mobilePhone: "--",
    userSexDesc: "--",
    userSourceDesc: "--",
    telephone: "--",
    certNo: "--",
    email: "--",
    address: "--",
    location: "--",
    remark: "暂无备注",
    statusDesc: "--",
    positionName: "--",
    deptNames: "--",
    mainDeptName: "--",
    certImg: certDefaultImg
  },
  sysUserForm: {
    id: "",
    userName: "",
    userCode: "",
    phone: "",
    labor: "",
    ifAllowDelete: "Y",
    validDate: dayjs(new Date()).add(1, "year").format("YYYY-MM-DD"),
    userType: "",
    status: "",
    avatar: userDefaultAvatar,
    avatarImg: "",
    roleIds: "",
    roleNames: ""
  },
  resetPasswordFormData: {
    id: "",
    password: "",
    confirmPassword: ""
  },
  formRules: {
    id: [{ required: true, message: "员工不能为空", trigger: "blur" }],
    userCode: [
      { required: true, message: "用户账号不能为空", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          const res = await validUserCode(state.sysUserForm);
          if (res.code != 200) {
            callback(new Error(res.msg));
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" }
    ],
    status: [{ required: true, message: "用户状态不能为空", trigger: "blur" }],
    roleIds: [{ required: true, message: "所属角色不能为空", trigger: "blur" }],
    validDate: [
      { required: true, message: "有效期限不能为空", trigger: "blur" }
    ],
    phone: [
      {
        validator: validMobilePhone,
        trigger: "change"
      }
    ]
  },
  resetPasswordFormRules: {
    password: [{ required: true, trigger: "blur", message: "新密码不能为空" }],
    confirmPassword: [
      { required: true, trigger: "blur", message: "确认密码不能为空" },
      {
        validator: function (rule, value, callback) {
          if (value != state.resetPasswordFormData.password) {
            return callback(new Error("两次密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ]
  }
});

onMounted(() => {
  state.sysUserForm.id = userid.value;
  state.sysUserForm.userName = usename.value;
  if (avatar) {
    state.sysUserForm.avatar = avatar.value;
  }
  queryStaffData();
  querySysUserData();
});

const queryStaffData = async () => {
  const { code, data } = await queryStaff(userid.value);
  if (code === 200 && data) {
    cloneObject(state.staffForm, data);
    if (!state.staffForm.certImg) {
      state.staffForm.certImg = certDefaultImg;
    }
  }
};

const handleSysUserCropperConfirm = value => {
  state.sysUserForm.avatarImg = value;
  state.sysUserForm.avatar = value;
};

const handlePictureCropperConfirm = async value => {
  const { code, msg } = await updateStaff({
    id: state.staffForm.id,
    certImg: value
  });
  if (code === 200) {
    state.staffForm.certImg = value;
    useMessage().success(msg);
  } else {
    state.staffForm.certImg = certDefaultImg;
    useMessage().error(msg);
  }
};

const querySysUserData = async () => {
  const { code, data } = await queryUser(userid.value);
  if (code === 200 && data) {
    console.log("querySysUserData", state.sysUserForm, data);
    cloneObject(state.sysUserForm, data);
    userStatusRef.value.setValue(state.sysUserForm.status);
    userTypeRef.value.setValue(state.sysUserForm.userType);
    if (state.sysUserForm.validDate) {
      state.sysUserForm.validDate = dayjs(state.sysUserForm.validDate).format(
        "YYYY-MM-DD"
      );
    }
    if (state.sysUserForm.avatarImg) {
      state.sysUserForm.avatar = state.sysUserForm.avatarImg;
    }
  }
};

const onSave = () => {
  sysUserFormRef.value.validate(async valid => {
    if (valid) {
      const { code, msg } = await updateUser(state.sysUserForm);
      if (code === 200) {
        userStore.SET_AVATAR(state.sysUserForm.avatar);
        useMessage().success(msg);
      } else {
        useMessage().error(msg);
      }
    }
  });
};

const handleResetSysUserAvatar = () => {
  const avatarImg = userDefaultAvatar;
  state.sysUserForm.avatar = avatarImg;
  state.sysUserForm.avatarImg = "";
  userStore.SET_AVATAR(avatarImg);
};

const onResetPassword = () => {
  state.resetPasswordFormData.id = userid.value;
  resetPasswordFormRef.value.validate(async valid => {
    if (valid) {
      const { code, msg } = await updateResetPassword(
        state.resetPasswordFormData
      );
      if (code === 200) {
        useMessage().success(msg);
      } else {
        useMessage().warning(msg);
      }
    }
  });
};

const handleUserTypeChange = val => {
  state.sysUserForm.userType = val;
};

const handleUserStatusChange = val => {
  state.sysUserForm.status = val;
};

const handleOpenStaffSelector = () => {
  staffRef.value.show();
};

const handleOpenRolePicker = () => {
  roleRef.value.show();
};

const handleUserSelect = rows => {
  if (rows) {
    state.sysUserForm.id = rows.id;
    state.sysUserForm.userName = rows.userName;
    state.sysUserForm.phone = rows.mobilePhone;
    state.sysUserForm.labor = rows.labor;
  }
  console.log("handleUserSelect", rows);
};

const handleRoleSelect = rows => {
  if (rows) {
    const roleIdList = [];
    const roleNameList = [];
    rows.forEach(item => {
      roleIdList.push(item.id);
      roleNameList.push(item.text);
    });
    state.sysUserForm.roleIds = roleIdList.join(",");
    state.sysUserForm.roleNames = roleNameList.join(",");
  }
};

const handleUserNameChange = () => {
  const userCode = pinyin.getCamelChars(state.sysUserForm.userName);
  state.sysUserForm.userCode = userCode.toLowerCase();
};

const handleOpenSysUserAvatarCropper = () => {
  sysUserCropperRef.value.dialogVisible = true;
};

const openPictureCropperDialog = () => {
  if (state.staffForm.id) {
    pictureCropperRef.value.show();
  }
};
</script>

<style lang="scss" scoped>
$base: ".info";

.info-sysuser {
  .card-content-full {
    height: calc(
      100vh - #{$base-nav-height} - #{$base-tabs-height} -
        (#{$base-padding} * 2) - 50px
    );
    overflow: auto;
  }
}

#{$base}-container {
  #{$base}-user-info {
    padding: $base-padding;
    text-align: center;

    :deep() {
      .el-avatar {
        img {
          cursor: pointer;
        }
      }
    }

    &-full-name {
      margin-top: 10px;
      font-size: 20px;
      font-weight: 500;
      color: #262626;
    }

    &-cert-img {
      width: 204px;
      height: 142.5px;
      border: 1px solid #dcdcdc;
    }

    &-description {
      margin-top: 8px;
    }

    &-follow {
      margin-top: 10px;
    }

    &-list {
      margin-top: 10px;
      margin-bottom: 0px;
      font-size: 16px;
      line-height: 30px;
      text-align: left;
      list-style: none;

      h5 {
        margin: 20px 0 5px 0;
      }

      :deep() {
        .el-tag {
          margin-right: 10px !important;
        }

        .el-tag + .el-tag {
          margin-left: 0;
        }
      }
    }
  }

  #{$base}-item {
    display: flex;

    i {
      font-size: 40px;
    }

    &-content {
      box-sizing: border-box;
      flex: 1;
      margin-left: $base-margin;

      &-second {
        margin-top: 8px;
      }
    }
  }
}
</style>
